<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;


class PayHaiWo
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $cacheClass;
    private $app_key = "NizfRngm3k3IiFIcGOR1TR4N";
    private $app_secret = "TYhYNDY8VymLuB9EROX6rrmPri8AxWJY1725008793";

    private $domain = "https://openapi.hiwork.com";

    public function __construct($config = [])
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function sign(string $data, string $iv = '')
    {
        $ivlen = openssl_cipher_iv_length('AES-128-CBC');
        $iv = openssl_random_pseudo_bytes($ivlen);

        $encrypt = openssl_encrypt($data, "AES-128-CBC", $this->app_secret, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv.$encrypt);
    }

    public function getHeader()
    {
        return [
            'CONTENT-TYPE' => 'application/json',
        ];
    }

    public function signAgree($id_card, $name, $phone)
    {
        $url = $this->domain . '/api/v3.0/individual/sign/agreement';

        $data = [
            "timestamp" => date('Y-m-d H:i:s'),
            'id_card' => $id_card,
            'name' => $name,
            'phone' => $phone,
            'sign_datetime' => date('Y-m-d H:i:s'),
            'business_type' => 1    ,
        ];

        $body = [
            "app_key" => $this->app_key,
            "sign" => $this->sign(json_encode($data))
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        Di::getDefault()->get("logger")->info("haiwo sign" . json_encode($json));

        if ($json['code'] == 22000) {
            return $json;
        }

        throw new Exception(9999, $json['message']);
    }

    public function queryOrder($orderId)
    {
        $url = $this->domain . '/api/v3.0/income/settlement/detail/fetch?';

        $data = [
            "timestamp" => date('Y-m-d H:i:s'),
            'income_source_id' => $orderId
        ];

        $body = [
            "app_key" => $this->app_key,
            "sign" => $this->sign(json_encode($data))
        ];

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }

    public function payOrder($orderId, $account, $name, $phone, $pay_money, $id_card, $payType = 3)
    {
        $url = $this->domain . '/api/v3.0/income/settlement/detail/create';

        $data = [
            "timestamp" => date('Y-m-d H:i:s'),
            'detail_data' => [
                [
                    'pay_channel' => $payType,
                    'notify_url' => 'https://api.doumvip.com/api/pay/haiwo_notify',
                    'income_source_id'=> $orderId,
                    'income_account' => $account,
                    'name' => $name,
                    'phone' => $phone,
                    'pay_money' => $pay_money,
                    'id_card' => $id_card,
                    'remark' => '抖啦咪数据助手提现'
                ]
            ]
        ];

        $body = [
            "app_key" => $this->app_key,
            "sign" => $this->sign(json_encode($data))
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && 22000 == $json['code']) {
            Di::getDefault()->get("logger")->info("haiwo payOrder" . json_encode($json));
            if ($json['result'][0]['status'] == 1) {
                return $json;
            } else {

            }  throw new Exception(9999, json_encode($json['result'][0]['error']));

        }

        throw new Exception(9999, $json['message']);
    }


}